from django.shortcuts import render,HttpResponse,reverse
from django.contrib.auth.hashers import make_password, check_password
from ..models import *
from django.http import JsonResponse
from .cates import get_cates_all
from .user import uploads_pic
import os
from django.contrib.auth.decorators import permission_required
#商品添加页面
@permission_required('myadmin.create_Goods',raise_exception=True)
def goods_add(request):
    #res=Cates.objects.all()
    data=get_cates_all()
    context={'context':data}
    #print(data)
    return render(request,'myadmin/goods_add.html',context)
#执行商品添加
@permission_required('myadmin.create_Goods',raise_exception=True)
def goods_insert(request):
    #print(request.POST.get('goodsinfo'))
    #接受所有数据
    try:
        data=request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        #处理分类 因为他本身是id 而表中需要存储一个 外键对象 从select框中的name
        data['cateid']=Cates.objects.get(id=data['cateid'])
        #判断是否是有图片
        myfile=request.FILES.get('pic',None)

        #如果没有则跳转上一个页
        if not myfile:
            return HttpResponse('<script>alert("必须上传商品图片");history.back(-1);</script>')
        #如果有继续执行 处理图片
        data['pic_url']=uploads_pic(myfile)

        #执行添加数据
        ob=Goods(**data)
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="/myadmin/goods_add/"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="/myadmin/goods_add/"</script>')
#商品列表
@permission_required('myadmin.show_Goods',raise_exception=True)
def goods_list(request):
    #获取全部数据
    data = Goods.objects.all()

    #搜索开始
    keyword = request.GET.get('keyword', None)
    types = request.GET.get('types', None)
    if types=='all':
        from django.db.models import Q
        data=Goods.objects.filter(Q(id__contains=keyword)|Q(goodsname__contains=keyword)|Q(title__contains=keyword))
    elif types:
        #如果不是all 并且是不假值 则进入这个条件
        #通过拼接字典的方式 把types+__contains  拼成 id__contains:keyword 这样的 字典格式
        search={types+'__contains':keyword}
        #把data()对象 的值进行过滤  条件是serach 字典中值
        data=data.filter(**search)

    #分页开始
    # 导入django分页模块
    from django.core.paginator import Paginator

    # 实例化对象 并且获取获取总页数
    p = Paginator(data, 10)

    # 获取当前页码数 如果没有传递get  默认是1
    pageindex = request.GET.get('page', 1)

    # 把导入的模块pag  使用对象p.page() 传递当前页数 默认是1  得到的结果是<userlist 1 of 15>
    # 意思是当前页码是1页 总共15页
    user_list = p.page(pageindex)

    context = {'userlist': user_list}
    #print(context)

    return render(request,'myadmin/goods_list.html',context)

#修改商品状态
@permission_required('myadmin.edit_Goods',raise_exception=True)
def goods_status(request):
    #print(request.GET.get('uid'))
    ob=Goods.objects.get(id=request.GET.get('uid'))
    ob.status=request.GET.get('status')
    ob.save()
    return JsonResponse({'msg': '状态更新成功', 'code': 0})

#修改商品名
@permission_required('myadmin.edit_Goods',raise_exception=True)
def goodsname(request):
    nikename=request.GET.get('nikename')
    id=request.GET.get('uid')
    #print(nikename,id)
    ob=Goods.objects.get(id=id)
    ob.goodsname=nikename
    ob.save()
    return HttpResponse('1')

#商品编辑
@permission_required('myadmin.edit_Goods',raise_exception=True)
def goods_edit(request):
    #print(request.GET.get('id'))
    #会员信息更新
    if request.method=='POST':
        uid = request.POST['uid']
        print(uid)
        ob = Goods.objects.get(id=uid)

        #更新头像
        myfile=request.FILES.get('pic',None)
        if myfile:
            try:
                os.remove('.'+ob.pic_url)
            except:
                pass
            ob.pic_url=uploads_pic(myfile)
        #更新其他信息
        cateid=request.POST.get('cateid')

        ob.cateid=Cates.objects.get(id=cateid)
        ob.goodsname=request.POST.get('goodsname')
        ob.title = request.POST.get('title')
        ob.price = request.POST.get('price')
        ob.goodsunm = request.POST.get('goodsunm')
        ob.goodsinfo = request.POST.get('goodsinfo')
        ob.ordernum = request.POST.get('ordernum')
        ob.clicknum = request.POST.get('clicknum')
        ob.status = request.POST.get('status')

        ob.save()
        return HttpResponse('<script>alert("更新成功");location.href="/myadmin/goods_list/";</script>')

    else:
        id=request.GET.get('id')
        data=Goods.objects.get(id=id)
        #把分类推送过去
        context = get_cates_all()
        #print(context)
        #必须使用values 否则返回的是{1:{对象}}
        return render(request,'myadmin/goods_edit.html',{'data':data,'context':context})
    #return HttpResponse('user_edit')

#商品删除
@permission_required('myadmin.remove_Goods',raise_exception=True)
def goods_del(request):
    id=request.GET.get('id')
    #print(id)
    try:
       ob = Goods.objects.get(id=id)
       ob.delete()
    except:
       pass
    return HttpResponse('<script>alert("删除成功");location.href="/myadmin/goods_list/";</script>')
